<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工单系统 - 工单详情</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            padding-top: 70px;
            padding-bottom: 30px;
        }
        .navbar-brand {
            color: #3949ab !important;
            font-weight: bold;
        }
        .card {
            margin-bottom: 20px;
            border: none;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        .ticket-status {
            font-size: 0.8rem;
            padding: 4px 10px;
            border-radius: 12px;
            display: inline-block;
        }
        .status-open {
            background-color: #e3f2fd;
            color: #1565c0;
        }
        .status-assigned {
            background-color: #fff8e1;
            color: #ffa000;
        }
        .status-resolved {
            background-color: #e8f5e9;
            color: #2e7d32;
        }
        .status-closed {
            background-color: #f5f5f5;
            color: #757575;
        }
        .priority-high {
            color: #d32f2f;
        }
        .priority-medium {
            color: #f57c00;
        }
        .priority-low {
            color: #388e3c;
        }
        .ticket-meta {
            color: #757575;
            font-size: 0.9rem;
        }
        .comment-item {
            border-left: 3px solid #e0e0e0;
            padding-left: 15px;
            margin-bottom: 20px;
        }
        .comment-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }
        .comment-author {
            font-weight: 500;
        }
        .comment-time {
            color: #757575;
            font-size: 0.85rem;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white fixed-top shadow-sm">
        <div class="container">
            <a class="navbar-brand" href="#">工单系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/static/tickets.html">所有工单</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/static/my-tickets.html">我的工单</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/static/assigned-tickets.html">分配给我的</a>
                    </li>
                    <li class="nav-item" id="admin-nav" style="display: none;">
                        <a class="nav-link" href="/static/metrics.html">统计信息</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <div class="dropdown">
                        <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="userDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                            <span id="username">用户</span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                            <li><a class="dropdown-item" href="/static/profile.html">个人资料</a></li>
                            <li><a class="dropdown-item" href="/static/change-password.html">修改密码</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" id="logout">退出登录</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container">
        <div class="mb-3">
            <a href="javascript:history.back()" class="btn btn-outline-secondary">
                <span>&larr; 返回</span>
            </a>
        </div>

        <!-- 工单详情 -->
        <div class="card mb-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h1 class="h3 mb-0" id="ticket-title">加载中...</h1>
                    <span class="ticket-status" id="ticket-status"></span>
                </div>
                <div class="ticket-meta mb-4">
                    <div><strong>创建者:</strong> <span id="ticket-creator">-</span></div>
                    <div><strong>创建时间:</strong> <span id="ticket-created-at">-</span></div>
                    <div id="ticket-assigned-container" style="display: none;">
                        <strong>处理人:</strong> <span id="ticket-assignee">-</span>
                    </div>
                    <div id="ticket-assigned-time-container" style="display: none;">
                        <strong>分配时间:</strong> <span id="ticket-assigned-at">-</span>
                    </div>
                    <div><strong>优先级:</strong> <span id="ticket-priority">-</span></div>
                </div>
                
                <h5>描述</h5>
                <div class="p-3 bg-light rounded mb-4" id="ticket-description">
                    加载中...
                </div>

                <!-- 工单操作区 -->
                <div class="d-flex gap-2 mb-4" id="ticket-actions">
                    <!-- 动态添加的操作按钮 -->
                </div>
            </div>
        </div>

        <!-- 评论区 -->
        <div class="card mb-4">
            <div class="card-header bg-white">
                <h5 class="mb-0">评论</h5>
            </div>
            <div class="card-body">
                <div id="comments-container">
                    <div class="text-center py-3" id="comments-loading">
                        <div class="spinner-border spinner-border-sm text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <span class="ms-2">加载评论...</span>
                    </div>
                    <div id="comments-list"></div>
                </div>

                <!-- 添加评论 -->
                <div class="mt-4">
                    <h6>添加评论</h6>
                    <form id="comment-form">
                        <div class="mb-3">
                            <textarea class="form-control" id="comment-content" rows="3" placeholder="请输入您的评论..." required></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary" id="submit-comment">提交评论</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 模态框：分配工单 -->
    <div class="modal fade" id="assignTicketModal" tabindex="-1" aria-labelledby="assignTicketModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="assignTicketModalLabel">分配工单</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="assign-ticket-form">
                        <div class="mb-3">
                            <label for="assignee-id" class="form-label">选择处理人</label>
                            <select class="form-select" id="assignee-id" required>
                                <option value="">-- 请选择处理人 --</option>
                                <!-- 用户列表将通过JavaScript动态加载 -->
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="assign-ticket-submit">确认分配</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 获取工单ID
        const urlParams = new URLSearchParams(window.location.search);
        const ticketId = urlParams.get('id');
        
        // 当前用户信息
        let currentUser = null;
        let assignModal = null;

        document.addEventListener('DOMContentLoaded', function() {
            // 检查用户是否已登录
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/static/index.html';
                return;
            }

            currentUser = JSON.parse(localStorage.getItem('user'));
            document.getElementById('username').textContent = currentUser.username;

            // 初始化模态框
            assignModal = new bootstrap.Modal(document.getElementById('assignTicketModal'));

            // 如果用户是管理员或客服，显示管理菜单
            if (currentUser.role === 'admin' || currentUser.role === 'support') {
                document.getElementById('admin-nav').style.display = 'block';
            }

            // 退出登录
            document.getElementById('logout').addEventListener('click', function(e) {
                e.preventDefault();
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                window.location.href = '/static/index.html';
            });

            // 如果没有工单ID，返回列表页
            if (!ticketId) {
                alert('无效的工单ID');
                window.history.back();
                return;
            }

            // 加载工单详情
            loadTicketDetails();
            
            // 加载评论
            loadComments();

            // 提交评论
            document.getElementById('comment-form').addEventListener('submit', function(e) {
                e.preventDefault();
                addComment();
            });

            // 分配工单
            document.getElementById('assign-ticket-submit').addEventListener('click', function() {
                const assigneeId = document.getElementById('assignee-id').value;
                if (!assigneeId) {
                    alert('请选择处理人');
                    return;
                }
                assignTicket(assigneeId);
            });
        });

        function loadTicketDetails() {
            // 显示加载状态
            document.getElementById('ticket-title').textContent = '加载中...';
            document.getElementById('ticket-description').textContent = '加载中...';
            
            fetch(`/api/tickets/${ticketId}`, {
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
            })
            .then(response => {
                if (response.status === 404) {
                    throw new Error('找不到该工单，可能已被删除或您没有权限查看');
                }
                return response.json();
            })
            .then(data => {
                if (data.code === 200) {
                    displayTicketDetails(data.data);
                } else {
                    document.getElementById('ticket-title').textContent = '加载失败';
                    document.getElementById('ticket-description').textContent = '出错了：' + data.message;
                    document.getElementById('ticket-actions').innerHTML = `
                        <button class="btn btn-primary" onclick="window.history.back()">返回列表</button>
                        <button class="btn btn-secondary ms-2" onclick="loadTicketDetails()">重试</button>
                    `;
                    alert('加载工单详情失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('获取工单详情失败:', error);
                document.getElementById('ticket-title').textContent = '加载失败';
                document.getElementById('ticket-description').textContent = '出错了：' + error.message;
                document.getElementById('ticket-actions').innerHTML = `
                    <button class="btn btn-primary" onclick="window.history.back()">返回列表</button>
                    <button class="btn btn-secondary ms-2" onclick="loadTicketDetails()">重试</button>
                `;
            });
        }

        function displayTicketDetails(ticket) {
            // 设置页面标题
            document.title = `工单 #${ticket.id}: ${ticket.title} - 工单系统`;
            
            // 填充工单基本信息
            document.getElementById('ticket-title').textContent = ticket.title;
            
            const statusElem = document.getElementById('ticket-status');
            statusElem.textContent = getStatusText(ticket.status);
            statusElem.className = `ticket-status status-${ticket.status}`;
            
            document.getElementById('ticket-creator').textContent = ticket.creator ? ticket.creator.username : '未知';
            document.getElementById('ticket-created-at').textContent = formatDate(ticket.created_at);
            
            const priorityElem = document.getElementById('ticket-priority');
            priorityElem.textContent = getPriorityText(ticket.priority);
            priorityElem.className = `priority-${ticket.priority}`;
            
            document.getElementById('ticket-description').textContent = ticket.description;
            
            // 处理分配信息
            if (ticket.assignee) {
                document.getElementById('ticket-assignee').textContent = ticket.assignee.username;
                document.getElementById('ticket-assigned-container').style.display = 'block';
                
                if (ticket.assigned_at) {
                    document.getElementById('ticket-assigned-at').textContent = formatDate(ticket.assigned_at);
                    document.getElementById('ticket-assigned-time-container').style.display = 'block';
                }
            }
            
            // 添加工单操作按钮
            const actionsContainer = document.getElementById('ticket-actions');
            actionsContainer.innerHTML = '';
            
            // 根据工单状态和用户角色添加不同的操作按钮
            const isAdmin = currentUser.role === 'admin';
            const isSupport = currentUser.role === 'support';
            const isAssignee = ticket.assignee && ticket.assignee.id === currentUser.id;
            const isCreator = ticket.creator && ticket.creator.id === currentUser.id;
            
            if ((isAdmin || isSupport) && ticket.status === 'open') {
                // 添加分配按钮
                const assignBtn = document.createElement('button');
                assignBtn.className = 'btn btn-primary';
                assignBtn.textContent = '分配工单';
                assignBtn.addEventListener('click', function() {
                    // 加载支持人员列表
                    loadSupportUsers();
                    // 显示分配模态框
                    assignModal.show();
                });
                actionsContainer.appendChild(assignBtn);
                
                // 如果是支持人员，添加接手按钮
                if (isSupport) {
                    const takeBtn = document.createElement('button');
                    takeBtn.className = 'btn btn-info ms-2';
                    takeBtn.textContent = '接手工单';
                    takeBtn.addEventListener('click', function() {
                        if (confirm('确定要接手此工单吗？')) {
                            takeTicket();
                        }
                    });
                    actionsContainer.appendChild(takeBtn);
                }
            }
            
            if ((isAdmin || isSupport || isAssignee) && ticket.status === 'assigned') {
                // 添加解决按钮
                const resolveBtn = document.createElement('button');
                resolveBtn.className = 'btn btn-success';
                resolveBtn.textContent = '标记为已解决';
                resolveBtn.addEventListener('click', function() {
                    if (confirm('确定要将此工单标记为已解决吗？')) {
                        resolveTicket();
                    }
                });
                actionsContainer.appendChild(resolveBtn);
            }
            
            if ((isAdmin || isCreator) && (ticket.status === 'resolved' || ticket.status === 'assigned')) {
                // 添加关闭按钮
                const closeBtn = document.createElement('button');
                closeBtn.className = 'btn btn-secondary';
                closeBtn.textContent = '关闭工单';
                closeBtn.addEventListener('click', function() {
                    if (confirm('确定要关闭此工单吗？')) {
                        closeTicket();
                    }
                });
                actionsContainer.appendChild(closeBtn);
            }
        }

        function loadComments() {
            document.getElementById('comments-loading').style.display = 'block';
            document.getElementById('comments-list').innerHTML = '';
            
            fetch(`/api/tickets/${ticketId}/comments`, {
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('comments-loading').style.display = 'none';
                
                if (data.code === 200) {
                    displayComments(data.data.comments);
                } else {
                    document.getElementById('comments-list').innerHTML = `<div class="text-center py-3">加载评论失败: ${data.message}</div>`;
                }
            })
            .catch(error => {
                document.getElementById('comments-loading').style.display = 'none';
                document.getElementById('comments-list').innerHTML = `<div class="text-center py-3">加载评论失败，请刷新重试</div>`;
                console.error('获取评论失败:', error);
            });
        }

        function displayComments(comments) {
            const commentsContainer = document.getElementById('comments-list');
            
            if (!comments || comments.length === 0) {
                commentsContainer.innerHTML = '<div class="text-center py-3">暂无评论</div>';
                return;
            }
            
            comments.forEach(comment => {
                const commentElem = document.createElement('div');
                commentElem.className = 'comment-item';
                commentElem.innerHTML = `
                    <div class="comment-header">
                        <span class="comment-author">${comment.user ? comment.user.username : '未知用户'}</span>
                        <span class="comment-time">${formatDate(comment.created_at)}</span>
                    </div>
                    <div class="comment-content">${comment.content}</div>
                `;
                commentsContainer.appendChild(commentElem);
            });
        }

        function addComment() {
            const content = document.getElementById('comment-content').value.trim();
            if (!content) {
                alert('请输入评论内容');
                return;
            }
            
            const submitBtn = document.getElementById('submit-comment');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '提交中...';
            
            fetch(`/api/tickets/${ticketId}/comments`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                },
                body: JSON.stringify({
                    content: content
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 201) {
                    // 重置表单
                    document.getElementById('comment-form').reset();
                    
                    // 重新加载评论
                    loadComments();
                } else {
                    alert('添加评论失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('添加评论请求失败:', error);
                alert('添加评论失败，请稍后再试');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '提交评论';
            });
        }

        function loadSupportUsers() {
            fetch('/api/users?role=support', {
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    const select = document.getElementById('assignee-id');
                    select.innerHTML = '<option value="">-- 请选择处理人 --</option>';
                    
                    data.data.users.forEach(user => {
                        const option = document.createElement('option');
                        option.value = user.id;
                        option.textContent = user.username;
                        select.appendChild(option);
                    });
                } else {
                    alert('获取支持人员列表失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('获取支持人员列表失败:', error);
                alert('获取支持人员列表失败，请稍后再试');
            });
        }

        function assignTicket(assigneeId) {
            fetch(`/api/tickets/${ticketId}/assign`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                },
                body: JSON.stringify({
                    assignee_id: parseInt(assigneeId)
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    // 关闭模态框
                    assignModal.hide();
                    
                    // 重新加载工单详情
                    loadTicketDetails();
                    
                    alert('工单分配成功');
                } else {
                    alert('分配工单失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('分配工单请求失败:', error);
                alert('分配工单失败，请稍后再试');
            });
        }

        function takeTicket() {
            fetch(`/api/tickets/${ticketId}/take`, {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    // 重新加载工单详情
                    loadTicketDetails();
                    
                    alert('工单接手成功');
                } else {
                    alert('接手工单失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('接手工单请求失败:', error);
                alert('接手工单失败，请稍后再试');
            });
        }

        function resolveTicket() {
            fetch(`/api/tickets/${ticketId}/resolve`, {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    // 重新加载工单详情
                    loadTicketDetails();
                    
                    alert('工单已标记为已解决');
                } else {
                    alert('解决工单失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('解决工单请求失败:', error);
                alert('解决工单失败，请稍后再试');
            });
        }

        function closeTicket() {
            fetch(`/api/tickets/${ticketId}/close`, {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    // 重新加载工单详情
                    loadTicketDetails();
                    
                    alert('工单已关闭');
                } else {
                    alert('关闭工单失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('关闭工单请求失败:', error);
                alert('关闭工单失败，请稍后再试');
            });
        }

        function getStatusText(status) {
            switch (status) {
                case 'open': return '未分配';
                case 'assigned': return '处理中';
                case 'resolved': return '已解决';
                case 'closed': return '已关闭';
                default: return status;
            }
        }

        function getPriorityText(priority) {
            switch (priority) {
                case 'low': return '低优先级';
                case 'medium': return '中优先级';
                case 'high': return '高优先级';
                default: return priority;
            }
        }

        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    </script>
</body>
</html> 